package com.example.its2021606134chh.BusModule;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.its2021606134chh.HttpUtil;
import com.example.its2021606134chh.R;
import com.example.its2021606134chh.TLModule.Lights;
import com.example.its2021606134chh.TLModule.TLightsRViewAdapter;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.Timer;
import java.util.TimerTask;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link BusFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class BusFragment extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "title";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private Timer timer;
    private TimerTask timerTask;
    private ExpandableListView expandListBus;
    //Model：定义的数据
    private String[] sList = {"1", "2"};
    private String[] allList = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15"};
    private int[] iList = {0, 1};
    private String[] groups = {"中医院站", "联想大厦站"};
    String s1Bus_1, s1Bus_2;
    String s2Bus_1, s2Bus_2;
    int Bus1_p, Bus2_p;
    private List<BusLists> list1 = new ArrayList<>();
    private List<BusLists> list2 = new ArrayList<>();
    private List<rvBusData> list = new ArrayList<>();
    //注意，字符数组不要写成{{"A1,A2,A3,A4"}, {"B1,B2,B3,B4，B5"}, {"C1,C2,C3,C4"}}
    private String[][] childs;
    private Button button3;

    public BusFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment BusFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static BusFragment newInstance(String param1, String param2) {
        BusFragment fragment = new BusFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_bus, container, false);
        expandListBus = (ExpandableListView) view.findViewById(R.id.expand_list_bus);
        button3 = (Button) view.findViewById(R.id.button3);
        button3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder dialog = new AlertDialog.Builder(getContext());
                View view2 = LayoutInflater.from(Objects.requireNonNull(getActivity()).getBaseContext()).inflate(R.layout.activity_dialog_rv_bus,null,false);
                dialog.setView(view2);
                Button btnBusCancel = (Button) view2.findViewById(R.id.btnBusCancel);
                RecyclerView rvBusList = (RecyclerView) view2.findViewById(R.id.rvDiaBusList);
                rvBusList.setLayoutManager(new LinearLayoutManager(getContext()));
                Timer timer1 = new Timer();
                TimerTask timerTask1 = new TimerTask() {
                    @Override
                    public void run() {
                        list.clear();
                        for (String s : allList) {
                            HttpUtil.asyncRequest(new HttpUtil.AsyncCallBack() {
                                @Override
                                public void onFailure(Exception e) {

                                }

                                @Override
                                public void onResponse(String json) {
                                    Gson gson = new Gson();
                                    Bus bus = gson.fromJson(json, Bus.class);
                                    Log.i("TAG", String.valueOf(bus.getBusCapacity()));
                                    list.add(new rvBusData(Integer.parseInt(s), bus.getBusCapacity()));
                                    rvBusList.setAdapter(new BusRViewAdapter(list));
                                }
                            }, "get_bus_capacity", new String[]{"BusId", "UserName"}, s, "user1");
                        }
                    }
                };
                timer1.schedule(timerTask1, 0, 3000);
                AlertDialog mdialog = dialog.show();
                btnBusCancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        timer1.cancel();
                        timerTask1.cancel();
                        mdialog.dismiss();
                    }
                });
            }
        });
        timer = new Timer();
        timerTask = new TimerTask() {
            @Override
            public void run() {
                list1.clear();
                list2.clear();
                for (String s : sList) {
                    HttpUtil.asyncRequest(new HttpUtil.AsyncCallBack() {
                        @Override
                        public void onFailure(Exception e) {

                        }

                        @Override
                        public void onResponse(String json) {
//                            Log.i("TAG", json);
                            Gson gson = new Gson();
                            BusStation station = gson.fromJson(json, BusStation.class);
                            List<BusStation.ROWSDETAILBean> Temp = station.getROWS_DETAIL();
                            HttpUtil.asyncRequest(new HttpUtil.AsyncCallBack() {
                                @Override
                                public void onFailure(Exception e) {

                                }

                                @Override
                                public void onResponse(String json) {
                                    Gson gson = new Gson();
                                    Bus bus = gson.fromJson(json, Bus.class);
                                    switch (s) {
                                        case "1":
                                            Bus1_p = bus.getBusCapacity();
                                            break;
                                        case "2":
                                            Bus2_p = bus.getBusCapacity();
                                            break;
                                        default:
                                            break;
                                    }
                                    for (int i = 0; i < 2; i++) {
                                        int BusId = Temp.get(i).getBusId();
                                        int Distance = Temp.get(i).getDistance();
                                        switch (s) {
                                            case "1":   //static 1
                                                if (BusId == 1) {
                                                    list1.add(new BusLists(BusId, Distance, Bus1_p));
                                                } else if (BusId == 2) {
                                                    list1.add(new BusLists(BusId, Distance, Bus2_p));
                                                }
                                                break;
                                            case "2":   //static 2
                                                if (BusId == 1) {
                                                    list2.add(new BusLists(BusId, Distance, Bus1_p));
                                                } else if (BusId == 2) {
                                                    list2.add(new BusLists(BusId, Distance, Bus2_p));
                                                }
                                                break;
                                            default:
                                                break;
                                        }
                                    }

//                                        排序
                                    Collections.sort(list1, new Comparator<BusLists>() {
                                        @Override
                                        public int compare(BusLists b1, BusLists b2) {
                                            if (b1.getDistance() > b2.getDistance()) {
                                                return 1;
                                            } else if (b1.getDistance() < b2.getDistance()) {
                                                return -1;
                                            }
                                            return 0;
                                        }
                                    });
                                    Collections.sort(list2, new Comparator<BusLists>() {
                                        @Override
                                        public int compare(BusLists b1, BusLists b2) {
                                            if (b1.getDistance() > b2.getDistance()) {
                                                return 1;
                                            } else if (b1.getDistance() < b2.getDistance()) {
                                                return -1;
                                            }
                                            return 0;
                                        }
                                    });
                                    for (int i = 0; i < list1.size(); i++) {
                                        if (i == 0) {
                                            s1Bus_1 = list1.get(i).getBusId() + "号(" + list1.get(i).getCapacity() + ")        " + (int) (((list1.get(i).getDistance() / 10) / 5.5) / 60) + "分钟到达                         " + " 距离站台" + list1.get(i).getDistance() / 10 + "米";
                                        } else if (i == 1) {
                                            s1Bus_2 = list1.get(i).getBusId() + "号(" + list1.get(i).getCapacity() + ")        " + (int) (((list1.get(i).getDistance() / 10) / 5.5) / 60) + "分钟到达                         " + " 距离站台" + list1.get(i).getDistance() / 10 + "米";
                                        }
                                    }
                                    for (int i = 0; i < list2.size(); i++) {
                                        if (i == 0) {
                                            s2Bus_1 = list2.get(i).getBusId() + "号(" + list2.get(i).getCapacity() + ")        " + (int) (((list2.get(i).getDistance() / 10) / 5.5) / 60) + "分钟到达                         " + " 距离站台" + list2.get(i).getDistance() / 10 + "米";
                                        } else if (i == 1) {
                                            s2Bus_2 = list2.get(i).getBusId() + "号(" + list2.get(i).getCapacity() + ")        " + (int) (((list2.get(i).getDistance() / 10) / 5.5) / 60) + "分钟到达                         " + " 距离站台" + list2.get(i).getDistance() / 10 + "米";
                                        }
                                    }
                                    childs = new String[][]{{s1Bus_1, s1Bus_2}, {s2Bus_1, s2Bus_2}};
                                    initView();
                                }
                            }, "get_bus_capacity", new String[]{"BusId", "UserName"}, s, "user1");
                        }
                    }, "get_bus_station_info", new String[]{"BusStationId", "UserName"}, s, "user1");
                }
            }
        };
        timer.schedule(timerTask, 0, 3000);
        return view;
    }

    private void initData() {

    }

    private void initView() {
        //        类似于RecycleView
        ExpandableListviewAdapter adapter = new ExpandableListviewAdapter(getContext(), groups, childs);
        expandListBus.setAdapter(adapter);
        //默认展开第一个数组
        expandListBus.expandGroup(0);
        expandListBus.expandGroup(1);

    }
}